using Aurora.HttpClient;
using Gateway.Common.Enums;
using Aurora.SingalR.Hubs;
using Gateway.UI.Api.TaskJobs;
using Microsoft.AspNetCore.Authorization;
using MediatR;
using System.Diagnostics;
using Aurora.Security.RSA.Util;
using Gateway.IApplication.Menu.Input;
using Gateway.UI.Api.Filters.Attributes;
using Aurora.TaskScheduler.Extension;
using Volo.Abp.EventBus.Distributed;

namespace Gateway.UI.Api.Controllers;

/// <summary>
/// 测试demo
/// </summary>
[AllowAnonymous]
public class DemoController : BaseController
{
    private readonly IHttpClient _client;

    private readonly IDistributedEventBus _distributedEventBus;

    // [HttpPost, Route("ocr")]
    // public string OCR([FromForm] IFormFile file)
    // {
    //     var ocr = new IronOcr.();
    // }
    private readonly IRSAUtil _rsa;
    private readonly HubHandlerProvider _hubHandler;

    private readonly TaskJobUtil _taskJobUtil;


    private readonly IMediator _mediator;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="rsa"></param>
    /// <param name="hubHandler"></param>
    /// <param name="client"></param>
    /// <param name="taskJobUtil"></param>
    /// <param name="mediator"></param>
    /// <param name="distributedEventBus"></param>
    public DemoController(IRSAUtil rsa, HubHandlerProvider hubHandler, IHttpClient client, TaskJobUtil taskJobUtil,
        IMediator mediator, IDistributedEventBus distributedEventBus) 
    {
        _rsa = rsa;
        _hubHandler = hubHandler;
        _client = client;
        _taskJobUtil = taskJobUtil;

        _mediator = mediator;
        _distributedEventBus = distributedEventBus;
        //_openAIService = openAIService;
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost, Route("enc")]
    public async Task<string> Enc([FromBody] string input)
    {
        var tt = await _rsa.EncryptAsync(input);
        return await _rsa.EncryptAsync(input);
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost, Route("des")]
    public async Task<string> Des([FromBody] string input)
    {
        var t = await _rsa.DecryptAsync(input);
        return t;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet, Route("publish/message")]
    public async Task<string> PublishMessage(string input)
    {
        await _hubHandler.Send(new HubMessage()
        { Creator = "sys", Message = "测试消息成功", Type = SendTypeEnum.Person.Value, User = "1636578588239216640" });
        return "1";
    }

    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    [HttpPost, Route("test/consul")]
    public async Task TestConsul()
    {
        await _client.GetAsync<string>("http://gateway-admin-api/api/health");
    }

    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    [HttpPost, Route("test/background/job")]
    public Task TestBackgroundJob()
    {
        _taskJobUtil.InvokeLater(typeof(TestBackgroundJob), new HubMessage()
        { Creator = "sys", Message = "测试消息成功", Type = SendTypeEnum.Person.Value, User = "1636578588239216640" });
        return Task.CompletedTask;
    }
    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    [HttpPost, Route("test/eventbus/create")]
    public Task TestEventBusCreate()
    {
        return Task.CompletedTask;
        // await _eventPublisher.PublishAsync(new ChannelEventSource("ToDo:Create", DateTime.Now));
    }
    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    [HttpPost, Route("test/eventbus/create/delay")]
    public Task TestEventBusDelayCreate()
    {
        return Task.CompletedTask;
        // await _eventPublisher.PublishDelayAsync(new ChannelEventSource("ToDo:Create", DateTime.Now), 3000);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    [HttpPost, Route("test/json/file")]
    public Task TestJsonFile()
    {
        var dir = Directory.GetCurrentDirectory();
        Console.WriteLine("dir is :" + dir);
        Debug.WriteLine("dir is :" + dir);
        string path = Path.Combine(dir, "Seed", "menu.json");
        string jsonData = GetJsonFile(path);
        var data = JsonConvert.DeserializeObject<List<UpdateMenuInput>>(jsonData);
        return Task.CompletedTask;
    }

    //获取到本地的Json文件并且解析返回对应的json字符串
    private static string GetJsonFile(string filepath)
    {
        string json = string.Empty;
        using (FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite,
                   FileShare.ReadWrite))
        {
            //Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            using (StreamReader sr = new StreamReader(fs))
            {
                json = sr.ReadToEnd().ToString();
            }
        }

        return json;
    }
    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    [HttpPost("test/event/stream"), SkipLogger]
    public Task TestEventStream()
    {
        return Task.CompletedTask;
        //var pro= HttpContext.Request.Protocol;
        //var response = Response;
        //响应头部添加text/event-stream，这是HTTP/2协议的一部分。
        //*HttpContext.Response.Headers.Add("Content-Type", "text/event-st*/ream");
        // HttpContext.Response.ContentType = "text/event-stream";
        //// 确保连接保持打开状态  
        //response.Headers.Add("Cache-Control", "no-cache");
        //response.Headers.Add("Connection", "keep-alive");
        // await  _openAIService.Chat(model, "", response);


        //await _openAIService.Chat(model, "",HttpContext);
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="message"></param>
    /// <param name="clientName"></param>
    /// <returns></returns>
    [HttpPost("test/rabbitmq/publish"), SkipLogger]
    public async Task TestRabbitmqPublish(string message, string clientName)
    {
        await _distributedEventBus.PublishAsync(new { message = message });
    }
}